// ==UserScript==
// @name         熊猫磁力
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://xiongmaoto.top/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=115.com
// @require      https://greasyfork.org/scripts/398240-gm-config-zh-cn/code/GM_config_zh-CN.js
// @grant        GM_registerMenuCommand
// @grant        GM_setValue
// @grant        GM_getValue

// ==/UserScript==

(function() {
    'use strict';

    // Your code here...
    //alert("blogjav start!");
	GM_config.init(
	{	
		prefix: {
			label: "前缀：",
			type: "text",
			default: "",
			description: "搜索前缀."
		},
		
		suffix: {
			label: "后缀：",
			type: "text",
			default: "",
			description: "搜索后缀."
		}
    });
 
    // Register a menu command to open settings
    GM_registerMenuCommand('设置', function() {
        GM_config.open();
    });

    changeFont();
    getMagnetList_syn();

    let searchStr = getQueryParam("searchstr");
    if (!searchStr) return;
	
	const prefixValue = GM_config.get('prefix');
	const suffixValue = GM_config.get('suffix');

    submitData(searchStr);

    function submitData(searchStr){
        let input = document.querySelector('#search-form input');
        let btn = document.querySelector('#search-form button');

        if (input) {
            input.value = prefixValue + searchStr + suffixValue;
            btn.click();
        }
    }

    function getQueryParam(param) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(param);
    }

    async function getMagnetList_syn(){
// 获取所有 '.panel-heading a' 元素
        const heading_list = document.querySelectorAll('.panel-heading');
        if (!heading_list) return;

        for (const heading of heading_list) {
			const link = heading.querySelector('a');
			const titleTxt = heading.textContent;
            await loadAndAppendMagnet(link, titleTxt); // 等待当前链接加载完成再继续下一个

            await delay(500);
        }

        // alert("磁力加载完成！");

        // 定义一个延迟函数，返回一个在指定毫秒后解析的Promise
        function delay(ms) {
            return new Promise(resolve => setTimeout(resolve, ms));
        }

        // 定义一个异步函数来处理单个链接的加载
        async function loadAndAppendMagnet(link, titleTxt) {
            try {
                const href = link.href;
                const response = await fetch(href); // 使用fetch API进行AJAX请求
                if (!response.ok) {
                    throw new Error(`Failed to load ${href} with status ${response.status}`);
                }
                const text = await response.text(); // 获取响应文本
                const parser = new DOMParser(); // 创建一个DOM解析器
                const doc = parser.parseFromString(text, 'text/html'); // 将文本解析为HTML文档
                const magnetElement = doc.querySelector('#magnet'); // 查找#magnet元素

                if (magnetElement) {
                    // 如果找到了#magnet元素，则将其克隆并添加到链接的父容器中
                    let div = document.createElement('div');
                    div.className = "panel-footer";

                    let magnetLink = magnetElement.href;
                    let imgHtml = '<img src="https://cdn.jsdelivr.net/gh/zxf10608/JavaScript/icon/115logo.ico" class="115offline" data-href='+magnetLink+' style="z-index:9123456789;display:inline-block;cursor:pointer;margin:0px 5px 2px;border-radius:50%;border:0px;vertical-align:middle;outline:none!important;padding:0px!important;height:20px!important;width:20px!important;left:0px!important;top:0px!important;" title="使用115网盘离线下载，右键复制地址\n'+magnetLink+'">';

                    div.appendChild(magnetElement.cloneNode(true));
                    div.innerHTML += imgHtml;
					
					// titleTxt = titleTxt.replace(/[a-zA-Z0-9]+\.[a-zA-Z]{2,3}/g, '');
					const code = getAVCode(titleTxt);
					if (code) {
						/* 生成弹窗 */
						let prewinBtn = document.createElement("button");
						prewinBtn.class = "normalBtn";
						prewinBtn.textContent = "弹窗";
						prewinBtn.style.marginLeft = '10px';
						prewinBtn.addEventListener("click", function (){
							// 弹出窗口的设置
							var newUrl = 'http://localhost:10168/site/premovie/index.html?avcode=' + code + '&avtitle=' + titleTxt;
							popupWindow(newUrl);
						});
						
						let longimgBtn = document.createElement("button");
						longimgBtn.class = "normalBtn";
						longimgBtn.textContent = "长图";
						longimgBtn.style.marginLeft = '10px';
						longimgBtn.addEventListener("click", function (){
							// 弹出窗口的设置
							var newUrl ="https://blogjav.net/?s=" + code + "&jump=true";
							popupWindow(newUrl);
						});
			
						div.appendChild(prewinBtn);
						div.appendChild(longimgBtn);
					}

                    link.parentElement.parentElement.parentElement.appendChild(div);
                }
            } catch (error) {
                console.error('Error loading or processing content:', error);
            }
        }
    }

    function changeFont(){
        const sssArr = document.querySelectorAll('.panel-footer h4 span');
        if (!sssArr) return;

        const regex = /(KB|MB|GB)/i;
        for (let sss of sssArr){
            if (regex.test(sss.textContent)){
                sss.style = `
                        font-size: 24px;
                        color: #45b71d;
                    `;
            }
        }
    }
	
	function popupWindow(newUrl, width = 1420, height = 960){
        var left = (window.screen.width - width)/2;
        var top = (window.screen.height - height)/2;
        var popupWindow = window.open(newUrl, '_blank', `left=${left}, top=${top} width=${width}, height=${height}`);
        // popupWindow.location.href = newUrl;
    }
	
	function getAVCode(titleStr){
            const regex = /[a-zA-Z]{2,5}-?[0-9]{2,5}/;
            const match = titleStr.match(regex);
            let avcode = null;
            if (match && match[0]) {
                avcode = match[0].toLowerCase();
            }

            if (!avcode) {
                avcode = titleStr;
            }

            return avcode;
        }

})();